﻿using System;

namespace OpenWaves.ImageTransformations
{
    public class ImageTransformationParser : IImageTransformationParser
    {
        public virtual bool TryParse(string value, out IImageTransformation transformation)
        {
            var separtorIndex = value.IndexOf('|');
            if (separtorIndex < 0)
            {
                transformation = null;
                return false;
            }

            var name = value.Substring(0, separtorIndex);
            var serializedProperties = value.Substring(separtorIndex + 1);

            return TryParse(name, serializedProperties, out transformation);
        }

        protected virtual bool TryParse(string name, string serializedProperties, out IImageTransformation transformation)
        {
            switch (name.ToUpperInvariant())
            {
                case "NULL":
                    transformation = ImageTransformation.Null;
                    return true;
                case "CENTRALCROP":
                    transformation = new CentralCropTransformation(serializedProperties);
                    return true;
                case "SCALETOFIT":
                    transformation = new ScaleToFitTransformation(serializedProperties);
                    return true;
                case "SCALEDOWNTOFIT":
                    transformation = new ScaleDownToFitTransformation(serializedProperties);
                    return true;
                case "SCALEDOWNTOFILL":
                    transformation = new ScaleDownToFillTransformation(serializedProperties);
                    return true;
                case "SCALETOFILL":
                    transformation = new ScaleToFillTransformation(serializedProperties);
                    return true;
                case "STRETCH":
                    transformation = new StretchTransformation(serializedProperties);
                    return true;
                default:
                    transformation = null;
                    return false;
            }
        }

        public virtual IImageTransformation Parse(string value)
        {
            IImageTransformation transformation;
            if (TryParse(value, out transformation) == false)
            {
                throw new FormatException("Failed to parse image transformation from string: " + value);
            }

            return transformation;
        }
    }
}
